package com.lagou.edu.controller;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.LagouUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/user")
public class LagouUserController {

    @Autowired
    private LagouUserService lagouUserService;


    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(HttpServletResponse response,
                            @PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code) {
        LagouToken lagouToken = JSON.parseObject(lagouUserService.register(email, password, code), LagouToken.class);
        if (lagouToken != null) {
            response.addCookie(new Cookie("token", lagouToken.getToken()));
            return true;
        }
        return false;
    }


    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        return lagouUserService.isRegistered(email);
    }


    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response,
                        @PathVariable String email,
                        @PathVariable String password) {
        LagouToken lagouToken = JSON.parseObject(lagouUserService.login(email, password), LagouToken.class);
        if (lagouToken != null) {
            //将token写入cookie中
            response.addCookie(new Cookie("token", lagouToken.getToken()));
            return lagouToken.getToken();
        }
        return "false";
    }


    @GetMapping("/info/{token}")
    public String getEmailByToken(@PathVariable String token) {
        return lagouUserService.getEmailByToken(token);
    }


}
